/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package apus.action.phonenumber;

import apus.action.Action;
import apus.action.ActionResult;
import apus.entity.*;
import apus.persistence.*;
import apus.services.ServiceLocator;
import java.io.UnsupportedEncodingException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Admin
 */
public class PhoneNumberSaveAction implements Action {

    @Override
    public ActionResult execute(HttpServletRequest request, HttpServletResponse response) {
        try {
            request.setCharacterEncoding("UTF-8");
        } catch (UnsupportedEncodingException ex) {
        }

        // if Save button have been pressed
        if (request.getParameter("saveButton") != null) {
            int id = Integer.parseInt(request.getParameter("id"));

            PhoneNumber phoneNumber = (id == 0) ? new RealPhoneNumber() : ServiceLocator.getService(PhoneNumberDAO.class).read(id);
            String number = request.getParameter("number");
            phoneNumber.setNumber(number);

            if (request.getParameter("sub_id") != null) {
                int sub_id = Integer.parseInt(request.getParameter("sub_id"));
                Subscriber sub;
                SubscriberDAO dao = ServiceLocator.getService(PersonDAO.class);
                /*(Integer.parseInt(request.getParameter("sub_type")) == 0)
                        ? ServiceLocator.getService(PersonDAO.class)
                        : ServiceLocator.getService(OrganizationDAO.class);*/
                sub = (Subscriber) dao.read(sub_id);
                phoneNumber.setOwner(sub);
            }


            PhoneNumberDAO phoneNumberDAO = ServiceLocator.getService(PhoneNumberDAO.class);
            if (id != 0) {
                phoneNumberDAO.update(phoneNumber); // update phoneNumber
                request.getSession().setAttribute("win", "Phone number was successfully updated");
            } else {
                phoneNumberDAO.create(phoneNumber); // create phoneNumber
                request.getSession().setAttribute("win", "Phone number was successfully added");
            }
        } else {
            request.getSession().setAttribute("fail", "Phone number data wasn't saved");
        }
        List<PhoneNumber> phoneNumberList = ServiceLocator.getService(PhoneNumberDAO.class).findAll();
        request.setAttribute("phoneNumberList", phoneNumberList);
        return ActionResult.redirect("phoneNumber.list");
    }

    @Override
    public String getName() {
        return "phoneNumber.save";
    }
}
